const authUtil = require('../../utils/auth')

Page({
  data: {
    projects: [],
    stats: {
      total: 0,
      active: 0,
      completed: 0
    },
    statusMap: {
      'planning': '规划中',
      'active': '进行中',
      'testing': '测试中',
      'completed': '已完成',
      'paused': '已暂停',
      'cancelled': '已取消'
    },
    // 登录状态相关
    isLoggedIn: false,
    loginChecked: false,
    currentUser: null
  },

  async onLoad() {
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: '我的项目'
    })
    
    // 执行登录检查
    await this.checkLoginStatus()
  },

  async onShow() {
    // 重新检查登录状态
    if (this.data.loginChecked) {
      await this.recheckLogin()
    } else {
      await this.checkLoginStatus()
    }
  },

  onPullDownRefresh() {
    this.refreshProjects()
  },

  // 🔐 检查登录状态
  async checkLoginStatus() {
    console.log('🔐 项目页面：开始登录检查...')
    
    this.setData({
      isLoggedIn: false,
      loginChecked: false,
      currentUser: null
    })
    
    const checkResult = await authUtil.performStrictLoginCheck()
    
    this.setData({
      isLoggedIn: checkResult.success,
      loginChecked: true,
      currentUser: checkResult.userInfo || null
    })
    
    if (checkResult.success) {
      console.log('✅ 项目页面：登录检查通过')
      await this.loadProjects()
    } else {
      console.log('❌ 项目页面：登录检查失败 -', checkResult.message)
      this.clearProjectData()
    }
    
    return checkResult
  },

  // 🔐 重新检查登录状态
  async recheckLogin() {
    const sessionValid = await authUtil.checkWechatSession()
    
    if (!sessionValid) {
      this.setData({
        isLoggedIn: false,
        loginChecked: true,
        currentUser: null
      })
      this.clearProjectData()
    } else if (this.data.isLoggedIn) {
      // 登录状态有效，刷新项目数据
      await this.loadProjects()
    }
  },

  // 🔐 要求登录
  requireLogin(callback) {
    if (!this.data.isLoggedIn || !this.data.loginChecked) {
      console.log('❌ 项目操作需要登录')
      authUtil.showLoginModal('需要登录', '查看项目需要先登录，是否立即前往登录？')
      return false
    }
    
    if (typeof callback === 'function') {
      return callback()
    }
    
    return true
  },

  // 清空项目数据
  clearProjectData() {
    this.setData({
      projects: [],
      stats: {
        total: 0,
        active: 0,
        completed: 0
      }
    })
  },

  // 刷新项目数据
  async refreshProjects() {
    if (!this.requireLogin()) {
      wx.stopPullDownRefresh()
      return
    }
    
    await this.loadProjects()
    wx.stopPullDownRefresh()
  },

  // 加载项目数据
  async loadProjects() {
    // 严格检查登录状态
    if (!this.data.isLoggedIn || !this.data.currentUser) {
      console.log('❌ 用户未登录，无法加载项目数据')
      this.clearProjectData()
      return
    }
    // 从订单中生成项目数据
    const orders = wx.getStorageSync('orders') || []
    const projects = wx.getStorageSync('projects') || []

    // 将已确认的订单转换为项目
    const confirmedOrders = orders.filter(order =>
      ['confirmed', 'surveying', 'designing', 'quoted', 'in_progress', 'testing', 'completed'].includes(order.status)
    )

    // 生成项目数据
    const generatedProjects = confirmedOrders.map(order => {
      const existingProject = projects.find(p => p.orderId === order.id)

      if (existingProject) {
        return existingProject
      }

      // 根据订单状态确定项目状态和进度
      let projectStatus = 'planning'
      let progress = 0

      switch (order.status) {
        case 'confirmed':
          projectStatus = 'planning'
          progress = 10
          break
        case 'surveying':
          projectStatus = 'active'
          progress = 25
          break
        case 'designing':
          projectStatus = 'active'
          progress = 40
          break
        case 'quoted':
          projectStatus = 'active'
          progress = 55
          break
        case 'in_progress':
          projectStatus = 'active'
          progress = 75
          break
        case 'testing':
          projectStatus = 'testing'
          progress = 90
          break
        case 'completed':
          projectStatus = 'completed'
          progress = 100
          break
      }

      return {
        id: 'PRJ' + order.id.substring(3),
        orderId: order.id,
        name: `${order.customerName} - ${order.serviceType}`,
        description: order.description,
        clientName: order.customerName,
        status: projectStatus,
        progress: progress,
        startDate: order.createTime,
        updateTime: order.updateTime
      }
    })

    // 保存项目数据
    wx.setStorageSync('projects', generatedProjects)

    // 计算统计数据
    const stats = {
      total: generatedProjects.length,
      active: generatedProjects.filter(p => p.status === 'active' || p.status === 'planning').length,
      completed: generatedProjects.filter(p => p.status === 'completed').length
    }

    this.setData({
      projects: generatedProjects,
      stats
    })
  },

  // 查看项目详情
  viewProjectDetail(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/project-detail/project-detail?id=${id}`
    })
  },

  // 显示登录提示
  showLoginModal() {
    authUtil.showLoginModal('需要登录', '查看项目需要先登录，是否立即前往登录？')
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return ''
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateStr === 'string') {
        date = new Date(dateStr)
      } else if (dateStr instanceof Date) {
        date = dateStr
      } else if (typeof dateStr === 'number') {
        date = new Date(dateStr)
      } else {
        date = new Date(String(dateStr))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('❌ 无效的日期格式:', dateStr)
        return String(dateStr)
      }
      
      // 手动格式化，确保兼容性
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      
      return `${year}年${month}月${day}日`
      
    } catch (error) {
      console.error('❌ 格式化日期失败:', error, '原始数据:', dateStr)
      return String(dateStr)
    }
  }
})